using UnityEngine;
using UnityEditor;
using UnityEngine.UI;
using UnityEngine.EventSystems;

public class UITemplateCreator
{
    [MenuItem("GameObject/UI/Create UI Template", false, 10)]
    public static void CreateUITemplate()
    {
        // 创建Canvas
        GameObject canvasGO = new GameObject("UICanvas");
        Canvas canvas = canvasGO.AddComponent<Canvas>();
        canvas.renderMode = RenderMode.ScreenSpaceOverlay;
        canvasGO.AddComponent<CanvasScaler>();
        canvasGO.AddComponent<GraphicRaycaster>();
        
        // 创建EventSystem（如果场景中没有的话）
        if (Object.FindObjectOfType<EventSystem>() == null)
        {
            GameObject eventSystemGO = new GameObject("EventSystem");
            eventSystemGO.AddComponent<EventSystem>();
            eventSystemGO.AddComponent<StandaloneInputModule>();
        }
        
        // 创建按钮
        GameObject buttonGO = new GameObject("Button");
        buttonGO.transform.SetParent(canvasGO.transform, false);
        
        // 添加RectTransform和设置大小
        RectTransform buttonRect = buttonGO.AddComponent<RectTransform>();
        buttonRect.sizeDelta = new Vector2(160, 30);
        
        // 添加Image组件
        Image buttonImage = buttonGO.AddComponent<Image>();
        buttonImage.color = Color.white;
        
        // 添加Button组件
        Button button = buttonGO.AddComponent<Button>();
        
        // 创建按钮文本
        GameObject textGO = new GameObject("Text");
        textGO.transform.SetParent(buttonGO.transform, false);
        
        RectTransform textRect = textGO.AddComponent<RectTransform>();
        textRect.anchorMin = Vector2.zero;
        textRect.anchorMax = Vector2.one;
        textRect.sizeDelta = Vector2.zero;
        textRect.offsetMin = Vector2.zero;
        textRect.offsetMax = Vector2.zero;
        
        Text text = textGO.AddComponent<Text>();
        text.text = "Button";
        text.font = Resources.GetBuiltinResource<Font>("Arial.ttf");
        text.fontSize = 14;
        text.alignment = TextAnchor.MiddleCenter;
        text.color = Color.black;
        
        // 设置按钮的目标图形
        button.targetGraphic = buttonImage;
        
        // 选中创建的对象
        Selection.activeGameObject = canvasGO;
        
        Debug.Log("UI模板已创建，包含Canvas、EventSystem和Button组件");
    }
}